package com.linuxgt.web.servlet;

import com.linuxgt.web.constant.Const;
import com.linuxgt.web.util.DateUtil;
import com.linuxgt.web.util.PropertiesUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;

import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

/**
 * web 初始化相关操作
 * Created by liuteng on 2016/11/25.
 */
@Component
public class InitServlet implements ServletContextAware {

    private final Logger log = LoggerFactory.getLogger(getClass());
    private static ServletContext servletContext;

    private String currentPattern = "dev";//当前系统运行模式
    private final Timer timer = new Timer();
    @Autowired
    private PropertiesUtils propertiesUtils;

    public ServletContext getServletContext() {
        return servletContext;
    }

    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }


    /**
     * spring bean初始化方法
     */
    @PostConstruct
    public void init() {

//      设置运行模式
        setPattern();

//      设置js版本号
        setjsversion();

        synchronized (timer) {
//        设置定时任务，当配置发生变化时更新ServletContext
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    String pattern = propertiesUtils.getMessage(Const.PATTERN);
                    if (StringUtils.isNotBlank(pattern) && !currentPattern.equals(pattern)) {
                        if (log.isDebugEnabled()) {
                            log.debug("old pattern value[{}],new pattern value[{}]",currentPattern, pattern);
                        }
                        currentPattern = pattern;
                        setPattern();
                    }
                }
            }, 0, 5000);
        }
    }

    /**
     * 设置应用运行模式
     */
    private void setPattern() {
        servletContext.setAttribute(Const.PATTERN, propertiesUtils.getMessage(Const.PATTERN));
    }

    /**
     * 设置js版本号
     */
    private void setjsversion() {
        Calendar calendar = Calendar.getInstance();
        String value = DateUtil.getFormatTimeString(calendar.getTime(), "yyyyMMddHHmmss");
        servletContext.setAttribute(Const.JSVERSION, value);
        log.debug("jsversion:{}", value);
    }
}
